import * as api from "@/api/api.js";
import * as config from "@/api/config.js";
import * as PatientApi from '@/api/hospital/patient.js';
import {
	WX_AUTH,
	STATE_KEY,
	BACK_URL
} from '@/config/cache';
import {
	parseQuery
} from '@/utils';
import store from '@/store';
import Cache from '@/utils/cache';

class AuthEHealth {

	constructor() {
		this.status = false; // 是否实例化
		this.initConfig = {};
	}
	
	/**
	 * 初始化
	 */
	EHealth() {
		return new Promise((resolve, reject) => {
			PatientApi.eHealthCfg().then(res => {
				console.table(res);
				this.initConfig = res.data;
				this.status = true;
				resolve(res.data);
			}).catch(err => {
				this.status = false;
				console.log('初始化失败 ', err);
				reject(err);
			});
		});
	}
	
	/**
	 * 健康列表页面
	 */
	toList(backUrl) {
		let that = this;
		let linkUrl = 'https://h5-health.tengmed.com/h5/tencent/open/card/regist';
		console.info("健康列表页面 toList");
		this.EHealth().then(cfg => {
			console.table(cfg);
			location.href = that.getAuthUrl(that.initConfig.hospitalId, linkUrl, backUrl);
			// that.getAuthUrl(that.initConfig.hospitalId, linkUrl, backUrl);
		})
	}
	
	/**
	 * 创建档案地址
	 */
	toCreate(backUrl) {
		let that = this;
		let linkUrl = 'https://h5-health.tengmed.com/h5/tencent/open/card/regist';
		this.EHealth().then(cfg => {
			location.href = that.getAuthUrl(that.initConfig.hospitalId, linkUrl, backUrl);
		})
	}
	
	/**
	 * 
	 * 获取跳转授权后的地址
	 */
	getAuthUrl(hospitalId,linkUrl,backUrl) {
		console.info("hospitalId:"+hospitalId);
		console.info("linkUrl:"+linkUrl);
		console.info("backUrl:"+backUrl);
		let url = `${location.origin}${backUrl}`
		console.info("url:"+url);
		if (url.indexOf('?') === -1) {
			url = url + '?'
		} else {
			url = url + '&'
		}
		console.info("url:"+url);
		const redirect_uri = encodeURIComponent(`${url}&hospitalId=${hospitalId}&p_back_url=` +
			encodeURIComponent(
				encodeURIComponent(
					backUrl ? backUrl : location.pathname + location.search
				)
			)
		);
		uni.removeStorageSync(BACK_URL);
		// const redirect_uri = encodeURIComponent(`${url}`);
		let authUrl =  `${linkUrl}?hospitalId=${hospitalId}&redirect_uri=${redirect_uri}`;
		console.info("authUrl:"+authUrl);
		return authUrl;
	}
	

	

}

export default new AuthEHealth();